package com.baibei.ebec.moments.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.baibei.ebec.home.R;
import com.baibei.ebec.home.R2;
import com.baibei.ebec.moments.adapter.MomentsHomeAdapter;
import com.baibei.ebec.sdk.ApiConstant;
import com.baibei.model.UserInfo;
import com.baibei.ui.AppUI;
import com.blankj.utilcode.utils.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.rae.swift.session.SessionManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MomentsInfoActivity extends AppCompatActivity {

    @BindView(R2.id.tv_banner_title)
    TextView tvBannerTitle;
    @BindView(R2.id.tv_username)
    TextView tvUsername;
    @BindView(R2.id.tv_follow)
    TextView tvFollow;
    @BindView(R2.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R2.id.tv_topicnum)
    TextView tvTopicnum;
    @BindView(R2.id.tv_follownum)
    TextView tvFollownum;
    @BindView(R2.id.tv_fansnum)
    TextView tvFansnum;
    @BindView(R2.id.tv_profit)
    TextView tvProfit;
    @BindView(R2.id.tv_teacher)
    TextView tvTeacher;
    @BindView(R2.id.tv_student)
    TextView tvStudent;
    @BindView(R2.id.rv)
    RecyclerView rv;
    private int type;
    private int userId;
    private int page = 1;
    private JSONObject json;
    private ArrayList<JSONObject> arrList;
    private boolean isRvSetAdapterAlready;
    private MomentsHomeAdapter mAdapter;
    private boolean isNoMoreData;
    private long checkId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_moments_info);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        //创建用来存储用户发帖内容的arraylist
        arrList = new ArrayList<>();
        //获取用户userId
        UserInfo userInfo = SessionManager.getDefault().getUser();
        userId = userInfo.getUserId();
        Intent intent = getIntent();
        //获取查询的用户id，如果没有，就是自身id
        checkId = intent.getLongExtra("checkId",userId);
        String userName = intent.getStringExtra("userName");
        String userAvatar = intent.getStringExtra("userAvatar");

        tvUsername.setText(userName);
        Glide.with(this).load(userAvatar).into(ivAvatar);

        //获取展示类型，如果是1，是自己的个人中心，如果是2，是其他用户的个人中心
        type = intent.getIntExtra("type", 0);
        if (type == 1) {
            tvBannerTitle.setText("我的点点圈");
            tvProfit.setText("我的收益");
            tvTeacher.setText("我的师父");
            tvStudent.setText("我的徒弟");
            tvFollow.setVisibility(View.GONE);
        } else if (type == 2) {
            tvBannerTitle.setText(userName+"的点点圈");
            tvProfit.setText("他的收益");
            tvTeacher.setText("他的师父");
            tvStudent.setText("他的徒弟");
            tvFollow.setVisibility(View.VISIBLE);
        }

        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                RecyclerView.LayoutManager layoutManager = rv.getLayoutManager();
                int lastVisiablePosition = -1;
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager llm = (LinearLayoutManager) layoutManager;
                    lastVisiablePosition = llm.findLastCompletelyVisibleItemPosition();
                }

                //判断是否已经滑到底页
                if (lastVisiablePosition == arrList.size() - 1) {
                    //判断是否已经没有更多数据可加载
                    if (json.has("count") && json.optInt("count") < 10) {
                        ToastUtils.showShortToast("没有更多数据了");
                        isNoMoreData = true;
                        return;
                    }
                    if (!isNoMoreData) {
                        AppUI.loading(MomentsInfoActivity.this);
                        page += 1;
                        getData();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

            }
        });

        getData();
    }

    private void getData() {
        String url = ApiConstant.API_BASE_URL + "ddq/api/v1/dataStatistic/findDataStatistic";
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",type==2?checkId:userId);
        netRequest(url, map, 1);
    }

    private void getTopicList() {
        String url = ApiConstant.API_BASE_URL + "ddq/api/v1/article/findArticleList";
        HashMap<String, Object> map = new HashMap<>();
        map.put("articleType", "4");
        map.put("userId",type==2?checkId:userId);
        map.put("pageNo", page);
        netRequest(url, map, 2);
    }

    //type指请求的类型，1是请求话题、关注、粉丝数量；2是请求用户帖子列表；3是关注按钮点击
    private void netRequest(final String url, final Map<String, Object> map, final int type) {
        AppUI.loading(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Gson gson = new Gson();
                String s = gson.toJson(map);
                RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .post(requestBody)
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    json = new JSONObject(response.body().string());
                    Log.i("jsonhhhh", json.toString());
                    AppUI.dismiss();
                    handler.post(type == 1 ? r1 : r2);
                } catch (IOException e) {
                    AppUI.dismiss();
                    e.printStackTrace();
                } catch (JSONException e) {
                    AppUI.dismiss();
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler = new Handler();

    Runnable r1 = new Runnable() {
        @Override
        public void run() {
            if (!"0".equals(json.optString("code"))){
                ToastUtils.showShortToast(json.optString("message"));
                getTopicList();
                return;
            }
            JSONArray data = json.optJSONArray("data");
            try {
                JSONObject job = data.getJSONObject(0);
                int bbsSum = job.optInt("bbsSum");
                int followerSum = job.optInt("followerSum");
                int userSum = job.optInt("userSum");

                tvTopicnum.setText(bbsSum + "");
                tvFollownum.setText(followerSum + "");
                tvFansnum.setText(userSum + "");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            getTopicList();
        }
    };

    Runnable r2 = new Runnable() {
        @Override
        public void run() {
            if (!"0".equals(json.optString("code"))){
                ToastUtils.showShortToast(json.optString("message"));
                return;
            }
            ArrayList<JSONObject> list = new ArrayList<>();
            try {
                JSONArray data = json.optJSONArray("data");
                for (int i = 0; i < data.length(); i++) {

                    list.add(data.getJSONObject(i));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (list != null) {
                arrList.addAll(list);
                if (!isRvSetAdapterAlready) {
                    LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext());
                    rv.setLayoutManager(llm);
                    mAdapter = new MomentsHomeAdapter(arrList);
                    rv.setAdapter(mAdapter);
                    isRvSetAdapterAlready = true;
                }
                mAdapter.setOnRecyclerViewItemClickListener(new MomentsHomeAdapter.onRecyclerViewItemClickListener() {
                    @Override
                    public void onClick(View view, MomentsHomeAdapter.ViewName viewName, int position) {
                        if (viewName == MomentsHomeAdapter.ViewName.ITEM) {
                            toBBSdetail(position);
                        }
                    }
                });
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
    };

    Runnable r3 = new Runnable() {
        @Override
        public void run() {
            ToastUtils.showShortToast(json.optString("message"));
            String code = json.optString("code");
            if ("0".equals(code)){
                //取消关注成功

            }


        }
    };

    private void toBBSdetail(int position) {
        JSONObject jsonObject = arrList.get(position);
        Intent intent = new Intent(MomentsInfoActivity.this, MomentsDetailActivity.class);
        intent.putExtra("content", jsonObject.toString());
        intent.putExtra("position", position);
        //fromType,跳转来源的类型，2是指从点点圈个人中心的帖子列表跳转过来的
        intent.putExtra("fromType",2);
        startActivityForResult(intent, 1);
    }


    @OnClick(R2.id.iv_back)
    public void onFinishClick() {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            //跳转帖子详情页，返回列表页时要将详情页改变的点赞数，点赞状态，评论数带回来并刷新
            int clickCount = data.getExtras().getInt("clickCount");
            int commentCount = data.getExtras().getInt("commentCount");
            String state = data.getExtras().getString("state");
            int position = data.getExtras().getInt("position");
            JSONObject jsonObject = arrList.get(position);
            try {
                jsonObject.put("clickCount", clickCount);
                jsonObject.put("commentCount", commentCount);
                jsonObject.put("state", state);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.i("jsonhhhhr", "there");
            mAdapter.notifyDataSetChanged();
        }
    }

    //查询关注
    @OnClick(R2.id.ll_follow)
    public void onQueryFollowClicked() {
        Intent intent = new Intent(MomentsInfoActivity.this, FollowAndFansListActivity.class);
        //用户种类，1是自己，2是他人
        intent.putExtra("userType", type);
        //查询的用户id
        intent.putExtra("userId", type==2?checkId:userId);
        //查询种类，1是查关注，2是查粉丝
        intent.putExtra("queryType", 1);
        startActivity(intent);
    }

    //查询粉丝
    @OnClick(R2.id.ll_fans)
    public void onQueryFansClicked() {
        Intent intent = new Intent(MomentsInfoActivity.this, FollowAndFansListActivity.class);
        //用户种类，1是自己，2是他人
        intent.putExtra("userType", type);
        //查询的用户id
        intent.putExtra("userId", userId);
        //查询种类，1是查关注，2是查粉丝
        intent.putExtra("queryType", 2);
        startActivity(intent);
    }

    //关注按钮点击
    @OnClick(R2.id.tv_follow)
    public void onFollowClicked() {
        if (type != 2){
            return;
        }
        String url = ApiConstant.API_BASE_URL+"ddq/api/v1/attention/addAttention";
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("followerId",checkId);
        netRequest(url,map,3);
    }
}
